import json

from rest_framework import generics
from django.http import JsonResponse
from django.db.models import Count
from .seralizers import AncientPoetrySerializer, AncientBooksSerializer
from .models import AncientPoetry, AncientBooks
from .filters import AncientPoetryFilter, AncientBooksFilter


class AncientPoetryListAPIView(generics.ListAPIView):
    queryset = AncientPoetry.objects.all().order_by("id")
    serializer_class = AncientPoetrySerializer
    filterset_class = AncientPoetryFilter


def get_ancient_poetry(request, pk):
    res = {"code": 400, "message": "", "data": None}
    try:
        data = AncientPoetry.objects.filter(id=pk).values().first()
        res["code"] = 200
        res["message"] = "success"
        data["content"] = data["content"].split("&")
        res["data"] = data
    except Exception as e:
        res["code"] = 500
        res["message"] = "服务器错误：" + str(e)
    finally:
        return JsonResponse(res)


def ancient_poetry_data_total_count(request):
    res = {"code": 400, "message": "",
           "data": {'dynasty_poems': [], 'author_poems': [], 'poet_count_author_by_dynasty': []}}
    try:
        dynasty_poems = list(AncientPoetry.objects.values('dynasty').annotate(poem_count=Count('id')))
        # 排除数量等于1的，且从大到小进行排序
        author_poems = list(AncientPoetry.objects.values('author').annotate(poem_count=Count('id')).exclude(poem_count__lte=1).order_by('poem_count'))
        poet_count_author_by_dynasty = list(AncientPoetry.objects.values('dynasty').annotate(author_count=Count('author', distinct=True)))
        res['code'] = 200
        res['message'] = 'success'
        res['data']['dynasty_poems'] = dynasty_poems
        res['data']['author_poems'] = author_poems
        res['data']['poet_count_author_by_dynasty'] = poet_count_author_by_dynasty
    except Exception as e:
        res["code"] = 500
        res["message"] = "服务器错误：" + str(e)
    finally:
        return JsonResponse(res)


class AncientBooksListAPIView(generics.ListAPIView):
    queryset = AncientBooks.objects.all().order_by("id")
    serializer_class = AncientBooksSerializer
    filterset_class = AncientBooksFilter


def get_ancient_books(request, pk):
    res = {"code": 400, "message": "", "data": None}
    try:
        data = AncientBooks.objects.filter(id=pk).values().first()
        res["code"] = 200
        res["message"] = "success"
        data["content"] = json.loads(data["content"])
        data['pic_url'] = 'http://127.0.0.1:9000/static/images/ancient-books/' + data['pic_url']
        res["data"] = data
    except Exception as e:
        res["code"] = 500
        res["message"] = "服务器错误：" + str(e)
    finally:
        return JsonResponse(res)
